import React from 'react';

import type { RouteObject } from 'react-router-dom';

import SvgIcon from '@/components/SvgIcon';

import type { MenuProps } from 'antd';

export * from './query';

export function getBaseChildrenRoutes(routes: RouteObject[]) {
  const baseRoutes = routes?.find(item => item.id === 'root')?.children;
  return baseRoutes ?? [];
}

/**
 * 根据路由配置生成菜单项
 * @param routes 路由配置数组
 * @returns Antd Menu 组件的 items 配置
 */
export function generateMenuFromRoutes(routes: RouteObject[]): MenuProps['items'] {
  const baseRoutes = getBaseChildrenRoutes(routes);

  return baseRoutes
    .filter(route => {
      // 过滤掉不需要在菜单中显示的路由
      return (
        route.handle?.constant &&
        route.handle?.title &&
        route.path !== '' &&
        !route.handle?.hideMenu // 添加 hideMenu 检查
      );
    })
    .map(route => transformRouteToMenuItem(route))
    .filter(Boolean);
}

/**
 * 将单个路由转换为菜单项
 * @param route 路由对象
 * @returns 菜单项配置
 */
function transformRouteToMenuItem(route: RouteObject): Router.MenuItem | null {
  if (!route.handle?.title) return null;

  const { title, icon, iconClass } = route.handle;
  const key = route.path || route.id || '';

  // 处理有子路由的情况
  if (route.children && route.children.length > 0) {
    const children = route.children
      .filter(
        child => child.handle?.constant && child.handle?.title && !child.handle?.hideMenu // 添加 hideMenu 检查
      )
      .map(child => ({
        key: `/${route.path}/${child.path}`.replace(/\/+/g, '/'),
        label: child.handle?.title,
        icon: child.handle?.icon
          ? getIconComponent(child.handle.icon, child.handle.iconClass)
          : undefined,
      }))
      .filter(Boolean);

    if (children.length > 0) {
      return {
        key: `/${key}`,
        label: title,
        icon: getIconComponent(icon, iconClass),
        children,
      };
    }
  }

  // 单个菜单项
  return {
    key: `/${key}`,
    label: title,
    icon: getIconComponent(icon, iconClass),
  };
}

/**
 * 根据图标名称获取图标组件
 * @param iconName 图标名称
 * @param iconClass 图标CSS类名
 * @returns React 图标组件
 */
function getIconComponent(iconName?: string, iconClass?: string) {
  if (!iconName) return undefined;

  // 创建一个包装组件来确保正确渲染
  return React.createElement(SvgIcon, {
    name: iconName,
    className: iconClass, // 应用自定义CSS类
    style: { fontSize: '16px' }, // 确保图标有合适的大小
  });
}

/**
 * 获取当前路由的面包屑信息
 * @param pathname 当前路径
 * @param routes 路由配置
 * @returns 面包屑数组
 */
export function getBreadcrumbFromRoute(
  pathname: string,
  routes: RouteObject[]
): Router.BreadcrumbItem[] {
  const baseRoutes = getBaseChildrenRoutes(routes);
  const breadcrumbs: Router.BreadcrumbItem[] = [];

  // 递归查找匹配的路由
  function findRoute(routes: RouteObject[], currentPath: string, parentPath = ''): boolean {
    for (const route of routes) {
      // 构建完整路径
      const fullPath = parentPath + '/' + (route.path || '');
      const normalizedPath = fullPath.replace(/\/+/g, '/').replace(/\/$/, '') || '/';

      // 检查是否匹配当前路径（支持动态路由参数）
      const isExactMatch = currentPath === normalizedPath;
      const isParentMatch = route.children && currentPath.startsWith(normalizedPath + '/');
      const isDynamicMatch =
        route.path?.includes(':') && matchDynamicRoute(normalizedPath, currentPath);

      if (isExactMatch || isParentMatch || isDynamicMatch) {
        // 添加到面包屑（只有有标题的才添加）
        if (route.handle?.title) {
          breadcrumbs.push({
            title: route.handle.title,
            path: normalizedPath === '/' ? undefined : normalizedPath,
          });
        }

        // 如果有子路由且当前路径不完全匹配，继续查找子路由
        if (route.children && currentPath !== normalizedPath && !isDynamicMatch) {
          return findRoute(route.children, currentPath, normalizedPath);
        }
        return true;
      }
    }
    return false;
  }

  // 匹配动态路由的辅助函数
  function matchDynamicRoute(routePath: string, currentPath: string): boolean {
    const routeSegments = routePath.split('/');
    const currentSegments = currentPath.split('/');

    if (routeSegments.length !== currentSegments.length) {
      return false;
    }

    for (let i = 0; i < routeSegments.length; i++) {
      const routeSegment = routeSegments[i];
      const currentSegment = currentSegments[i];

      // 如果是动态参数（以:开头），跳过检查
      if (routeSegment.startsWith(':')) {
        continue;
      }

      // 如果不是动态参数，必须完全匹配
      if (routeSegment !== currentSegment) {
        return false;
      }
    }

    return true;
  }

  findRoute(baseRoutes, pathname);

  // 特殊处理：如果是产品详情页面，需要手动添加产品列表的面包屑
  if (pathname.includes('/equipment/product/detail/')) {
    // 检查是否已经有产品列表的面包屑
    const hasProductList = breadcrumbs.some(item => item.title === '产品列表');
    if (!hasProductList) {
      // 在产品详情之前插入产品列表
      const detailIndex = breadcrumbs.findIndex(item => item.title === '产品详情');
      if (detailIndex > 0) {
        breadcrumbs.splice(detailIndex, 0, {
          title: '产品列表',
          path: '/equipment/product',
        });
      }
    }
  }

  return breadcrumbs;
}

/**
 * 获取当前激活的菜单键
 * @param pathname 当前路径
 * @returns 激活的菜单键数组
 */
export function getActiveMenuKeys(pathname: string): string[] {
  const segments = pathname.split('/').filter(Boolean);
  const keys: string[] = [];

  let currentPath = '';
  for (const segment of segments) {
    currentPath += `/${segment}`;
    keys.push(currentPath);
  }

  return keys;
}

/**
 * 获取默认展开的菜单键
 * @param routes 路由配置
 * @returns 默认展开的菜单键数组
 */
export function getDefaultOpenKeys(routes: RouteObject[]): string[] {
  const baseRoutes = getBaseChildrenRoutes(routes);

  return baseRoutes
    .filter(route => route.children && route.children.length > 0)
    .map(route => `/${route.path || ''}`)
    .filter(Boolean);
}
